<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEnvironments, deleteEnvironment, createEnvironment, updateEnvironment, getProjectDetail } from '@/api/index.js'
import { Plus, Edit, Delete, ArrowLeft } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import KeyValueEditor from '@/components/KeyValueEditor.vue'

// 添加防抖功能
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

const router = useRouter()
const route = useRoute()
const projectId = route.params.id

const environments = ref([])
const loading = ref(false)
const createDialogVisible = ref(false)
const editDialogVisible = ref(false)
const createLoading = ref(false)
const editLoading = ref(false)
const currentEditId = ref(null)
const projectInfo = ref({})

const searchForm = ref({
  name: ''
})

const environmentForm = ref({
  name: '',
  base_url: '',
  variables: {},
  headers: {}
})

const editForm = ref({
  name: '',
  base_url: '',
  variables: {},
  headers: {}
})

const formRules = {
  name: [
    { required: true, message: '请输入环境名称', trigger: 'blur' },
    { min: 2, max: 50, message: '环境名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  base_url: [
    { required: true, message: '请输入基础URL', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入基础URL'))
          return
        }
        
        // 检查是否为有效的HTTP/HTTPS URL
        const urlPattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/
        if (!urlPattern.test(value)) {
          callback(new Error('请输入有效的HTTP或HTTPS地址'))
          return
        }
        
        // 检查是否以斜杠结尾（不允许）
        if (value.endsWith('/')) {
          callback(new Error('基础URL不能以斜杠(/)结尾，如：http://101.43.72.189:8889'))
          return
        }
        
        callback()
      }, 
      trigger: 'blur' 
    }
  ]
}

const environmentFormRef = ref()
const editFormRef = ref()

const fetchEnvironments = async () => {
  loading.value = true
  try {
    const params = {
      project_id: projectId,
      name: searchForm.value.name
    }
    const res = await getEnvironments(params)
    if (res.status === 200) {
      environments.value = res.data.results || res.data || []
    }
  } catch (error) {
    ElMessage.error('获取环境配置列表失败')
  } finally {
    loading.value = false
  }
}

const fetchProjectInfo = async () => {
  try {
    const res = await getProjectDetail(projectId)
    if (res.status === 200) {
      projectInfo.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取项目信息失败')
  }
}

const debouncedSearch = debounce(() => {
  fetchEnvironments()
}, 500)

const handleSearch = () => {
  fetchEnvironments()
}

const handleInputSearch = () => {
  debouncedSearch()
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除环境配置 "${row.name}" 吗？此操作不可撤销！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const res = await deleteEnvironment(row.id)
    
    // 检查后端返回的 status 字段（现在是 200）
    if (res && res.status === 200) {
      ElMessage.success(res.msg || '删除成功')
      await fetchEnvironments()
    } else {
      ElMessage.error(`删除失败: ${res?.msg || '未知错误'}`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除环境配置出错:', error)
      // 如果是网络错误或其他错误
      if (error.response) {
        // 服务器响应了错误状态码
        ElMessage.error(`删除失败: ${error.response.data?.msg || error.response.statusText}`)
      } else if (error.request) {
        // 请求已发出但没有收到响应
        ElMessage.error('删除失败: 网络错误')
      } else {
        // 其他错误
        ElMessage.error(`删除失败: ${error.message}`)
      }
    }
  }
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch (error) {
    return '-'
  }
}

const showCreateDialog = () => {
  createDialogVisible.value = true
  environmentForm.value = {
    name: '',
    base_url: '',
    variables: {},
    headers: {}
  }
}

const handleCreateSubmit = async () => {
  if (!environmentFormRef.value) return
  
  await environmentFormRef.value.validate(async (valid) => {
    if (valid) {
      createLoading.value = true
      try {
        const formData = {
          ...environmentForm.value,
          project: projectId,
          variables: environmentForm.value.variables,
          headers: environmentForm.value.headers
        }
        
        const res = await createEnvironment(formData)
        // 检查后端返回的 status 字段
        if (res && res.status === 201) {
          ElMessage.success(res.msg || '环境配置创建成功')
          createDialogVisible.value = false
          await fetchEnvironments()
        } else {
          ElMessage.error(`环境配置创建失败: ${res?.msg || '未知错误'}`)
        }
      } catch (error) {
        console.error('创建环境配置错误:', error)
        ElMessage.error(`环境配置创建失败: ${error.response?.data?.msg || error.message}`)
      } finally {
        createLoading.value = false
      }
    }
  })
}

const handleCreateCancel = () => {
  createDialogVisible.value = false
  environmentForm.value = {
    name: '',
    base_url: '',
    variables: {},
    headers: {}
  }
}

const handleEdit = (row) => {
  currentEditId.value = row.id
  editForm.value = {
    name: row.name,
    base_url: row.base_url,
    variables: row.variables || {},
    headers: row.headers || {}
  }
  editDialogVisible.value = true
}

const handleEditSubmit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (valid) {
      editLoading.value = true
      try {
        const formData = {
          ...editForm.value,
          project: projectId,
          variables: editForm.value.variables,
          headers: editForm.value.headers
        }
        
        const res = await updateEnvironment(currentEditId.value, formData)
        // 检查后端返回的 status 字段
        if (res && res.status === 200) {
          ElMessage.success(res.msg || '环境配置更新成功')
          editDialogVisible.value = false
          await fetchEnvironments()
        } else {
          ElMessage.error(`环境配置更新失败: ${res?.msg || '未知错误'}`)
        }
      } catch (error) {
        console.error('更新环境配置错误:', error)
        ElMessage.error(`环境配置更新失败: ${error.response?.data?.msg || error.message}`)
      } finally {
        editLoading.value = false
      }
    }
  })
}

const handleEditCancel = () => {
  editDialogVisible.value = false
  editForm.value = {
    name: '',
    base_url: '',
    variables: {},
    headers: {}
  }
  currentEditId.value = null
}

const goBack = () => {
  router.push('/projects')
}

onMounted(() => {
  fetchProjectInfo()
  fetchEnvironments()
})
</script>

<template>
  <div class="environment-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-button :icon="ArrowLeft" @click="goBack">返回项目列表</el-button>
            <span class="project-title">{{ projectInfo.name }} - 环境配置管理</span>
          </div>
          <el-button type="primary" :icon="Plus" @click="showCreateDialog">
            新建环境配置
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="环境名称">
            <el-input v-model="searchForm.name" placeholder="请输入环境名称" clearable @input="handleInputSearch" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="environments" v-loading="loading" stripe>
        <el-table-column prop="name" label="环境名称" />
        <el-table-column prop="base_url" label="基础URL" show-overflow-tooltip />
        <el-table-column label="环境变量" width="120">
          <template #default="scope">
            <el-tag>{{ Object.keys(scope.row.variables || {}).length }} 个变量</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="全局请求头" width="120">
          <template #default="scope">
            <el-tag>{{ Object.keys(scope.row.headers || {}).length }} 个请求头</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_time || scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" :icon="Edit" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" :icon="Delete" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty v-if="!loading && environments.length === 0" description="暂无环境配置，点击上方按钮创建" />
    </el-card>

    <!-- 创建环境配置对话框 -->
    <el-dialog 
      v-model="createDialogVisible" 
      title="创建环境配置" 
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="environmentFormRef"
        :model="environmentForm"
        :rules="formRules"
        label-width="100px"
        size="default"
      >
        <el-form-item label="环境名称" prop="name">
          <el-input
            v-model="environmentForm.name"
            placeholder="请输入环境名称，如：开发环境、测试环境"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="基础URL" prop="base_url">
          <el-input
            v-model="environmentForm.base_url"
            placeholder="请输入基础URL，如：http://101.43.72.189:8889（不要以/结尾）"
          />
          <div class="help-text">
            <el-text size="small" type="info">
              基础URL格式示例：http://101.43.72.189:8889，注意不要以斜杠(/)结尾
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="环境变量">
          <KeyValueEditor
            v-model="environmentForm.variables"
            title="环境变量"
            key-placeholder="变量名"
            value-placeholder="变量值"
          />
          <div class="help-text">
            <el-text size="small" type="info">
              环境变量将在测试用例中可用，如：api_key、timeout、version 等
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="全局请求头">
          <KeyValueEditor
            v-model="environmentForm.headers"
            title="全局请求头"
            key-placeholder="请求头名称"
            value-placeholder="请求头值"
          />
          <div class="help-text">
            <el-text size="small" type="info">
              全局请求头将自动添加到此环境的所有请求中，如：Content-Type、Authorization 等
            </el-text>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCreateCancel">取消</el-button>
          <el-button type="primary" @click="handleCreateSubmit" :loading="createLoading">
            创建
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑环境配置对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑环境配置" 
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="formRules"
        label-width="100px"
        size="default"
      >
        <el-form-item label="环境名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入环境名称，如：开发环境、测试环境"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="基础URL" prop="base_url">
          <el-input
            v-model="editForm.base_url"
            placeholder="请输入基础URL，如：http://101.43.72.189:8889（不要以/结尾）"
          />
          <div class="help-text">
            <el-text size="small" type="info">
              基础URL格式示例：http://101.43.72.189:8889，注意不要以斜杠(/)结尾
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="环境变量">
          <KeyValueEditor
            v-model="editForm.variables"
            title="环境变量"
            key-placeholder="变量名"
            value-placeholder="变量值"
          />
          <div class="help-text">
            <el-text size="small" type="info">
              环境变量将在测试用例中可用，如：api_key、timeout、version 等
            </el-text>
          </div>
        </el-form-item>

        <el-form-item label="全局请求头">
          <KeyValueEditor
            v-model="editForm.headers"
            title="全局请求头"
            key-placeholder="请求头名称"
            value-placeholder="请求头值"
          />
          <div class="help-text">
            <el-text size="small" type="info">
              全局请求头将自动添加到此环境的所有请求中，如：Content-Type、Authorization 等
            </el-text>
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditCancel">取消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="editLoading">
            更新
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.environment-management {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .project-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }

  .search-area {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .help-text {
    margin-top: 8px;
    
    .el-text {
      line-height: 1.4;
    }
  }
}
</style>